const http = require('http');
const content = require('./util/content')
const proxy = require('http-proxy-middleware')
const mimeTypes = require('./util/mimeTypes')
const path = require('path');


//静态资源的路径
const statPath = __dirname + '/www';

//解决History强制刷新的问题
function refershHistory(res) {
  res.writeHead(302, {
    'location': 'http://localhost:3000/'
  })
  res.end();
  return false;
}

//设置代理
function setProxy(url, req, res) {
  if (/\/api/.test(url)) {
    console.log('proxy')
    let options = {
      target: 'http://localhost:3005',
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    }
    let statProxy = proxy(options);
    return statProxy(req, res)
  }

  if (/\/static/.test(url)) {
    console.log('proxy')
    let options = {
      target: 'https://www.lgstatic.com',
      changeOrigin: true,
      pathRewrite: {
        '^/static': ''
      }
    }
    let statProxy = proxy(options);
    return statProxy(req, res)
  }
}


var app = http.createServer((req, res) => {
  let url = req.url;
  //默认索引页
  if (url === '/') {
    url = "/index.html"
  }

  //history强制刷新问题
  if (/\?position|search|profile/.test(url)) {
    return refershHistory(res);
  }

  //代理
  if (/\/api/.test(url) || /\/static/.test(url)) {
    return setProxy(url, req, res);
  }

  let extname = path.extname(url).substring(1);
  let conentType = mimeTypes[extname] ? mimeTypes[extname] : "text/html";
  res.setHeader('Content-Type', conentType)
  let result = content(url, statPath);
  res.write(result);
  res.end();

})

app.listen(3000, function (err) {
  if (!err) {
    console.log('localhost 3000 start ...')
  }
})


